package lj.netty;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.log.StaticLog;
import io.netty.handler.codec.ByteToMessageDecoder;
import lj.netty.bean.LJNettyBo;
import lj.netty.bean.LJNettyInitContext;
import lj.netty.bean.LJNettyMsgContext;
import lj.netty.channel.ChannelHandlerCommon;
import lj.netty.listen.LJCNettyListen;
import lj.netty.listen.LJNettyListen;
import lombok.NoArgsConstructor;
import ntd.tool.abnormal.ComAbnormal;

/**
 * @author: liuwenju
 * @date: 2023/6/5 16:53
 * @version: 1.0
 */
@NoArgsConstructor
public class ToolNettyInit {

    /** 上下文对象 */
    private LJNettyInitContext ljNettyInitContext;

    /** netty 服务对象 */
    private ComAbsNettyTcp comAbsNettyTcp;

    public ToolNettyInit(LJNettyInitContext ljNettyInitContext) {
        this.ljNettyInitContext = ljNettyInitContext;

        if (ObjectUtil.isNull(ljNettyInitContext.getPort())) {
            throw new ComAbnormal("端口不能为空...");
        }
        // 初始化netty链接对象
        if (StrUtil.isBlank(ljNettyInitContext.getHost())) {
            this.comAbsNettyTcp = new ComNettyTcp(ljNettyInitContext.getPort());
        } else {
            this.comAbsNettyTcp = new ComNettyTcpClient(ljNettyInitContext.getHost(), ljNettyInitContext.getPort());
        }
        ljNettyInitContext.setChannelHandlerCommon(new ChannelHandlerCommon(comAbsNettyTcp, ljNettyInitContext.getLJCNettyListen()));

        this.comAbsNettyTcp.ljNettyInitContext = ljNettyInitContext;
    }

    public void start() {
        // 启动netty 链接
        this.comAbsNettyTcp.start();
    }

    public void close() {
        this.comAbsNettyTcp.close();
    }

    public static void main(String[] args) {
        LJNettyInitContext ljNettyInitContext1 = new LJNettyInitContext();

        ljNettyInitContext1.setPort(36059);
        ljNettyInitContext1.setLJCNettyListen(new LJCNettyListen() {
            @Override
            public void onInit(LJNettyBo LJNettyBo) {

            }

            @Override
            public void onMsg(LJNettyBo LJNettyBo) {
                StaticLog.info(new String(LJNettyBo.getBytes()));
            }

            @Override
            public void onClose(LJNettyBo LJNettyBo) {

            }

            @Override
            public ByteToMessageDecoder struct() {
                return null;
            }
        });

        ToolNettyInit toolNettyInit = new ToolNettyInit(ljNettyInitContext1);

        toolNettyInit.start();
    }

}
